package com.jn.web;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.jn.entity.account.User;
import com.jn.service.account.AccountService;

/**
 * @ClassName RegisterController
 * @Description 用户注册的Controller
 * @author liuxd
 * @date 2013年8月27日 上午10:59:02
 * 
 */
@Controller
@RequestMapping(value = "/register")
public class RegisterController {

	@Autowired
	private AccountService accountService;

	/**
	 * @Title registerForm
	 * @Description 初始化register页面
	 * @return
	 * @throws
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String registerForm() {
		return "account/register";
	}

	/**
	 * @Title register
	 * @Description 注册
	 * 		@Valid 注解释义：
	 * 		将页面上的数据封装为User对象
	 * 		要求：页面上的input等收入框的name必须与user对象的属性相对应
	 * 		P.s. 也可以使用HttpServletRequest对象自己获取并封装成User对象
	 * @param user
	 * @param redirectAttributes
	 * @return
	 * @throws
	 */
	@RequestMapping(method = RequestMethod.POST)
	public String register(@Valid User user,
			RedirectAttributes redirectAttributes) {
		accountService.registerUser(user);
		redirectAttributes.addFlashAttribute("username", user.getLoginName());
		return "redirect:/login";
	}

	/**
	 * Ajax请求校验loginName是否唯一
	 */
	@RequestMapping(value = "checkLoginName")
	@ResponseBody
	public String checkLoginName(@RequestParam("loginName") String loginName) {
		if (accountService.findUserByLoginName(loginName) == null) {
			return "true";
		} else {
			return "false";
		}
	}
}
